package com.bianmaba.oauth2.authserver.config;

import com.bianmaba.spring.security.basic.BasicSecurityProperties;
import com.bianmaba.spring.security.database.DatabaseWebSecurityCongigurerAdapter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class CustomWebSecurityConfigurerAdapter extends DatabaseWebSecurityCongigurerAdapter {
    @Autowired
    private BasicSecurityProperties securityProperties;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        // http.addFilterAfter(sessionChangedFilter(), UsernamePasswordAuthenticationFilter.class);
        http.logout().permitAll().logoutSuccessHandler(new LogoutSuccessHandler() {

            @Override
            public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                String redirect = request.getParameter("redirect_uri");
                if (!StringUtils.isEmpty(securityProperties.getLogoutSuccessUrl())) {
                    redirect = securityProperties.getLogoutSuccessUrl();
                } else {
                    if (redirect == null || redirect.trim().isEmpty()) {
                        redirect = "/";
                    }
                }
                response.sendRedirect(redirect);
            }
        });
    }
}
